<?php
/**
 * 栏目数据
 */
namespace app\common\model;

use think\Model;

class Category extends Model
{
    // 开启自动写入时间戳字段
    // protected $autoWriteTimestamp = true;
    // 定义时间戳字段名，默认为create_time，update_time
    // protected $createTime = 'create_time';
    // protected $updateTime = 'update_time';

    // 添加栏目
    public function add($data)
    {
        $data['status'] = 1;
        $data['create_time'] = time();
        return $this->save($data);
    }

    // 查询获取顶级栏目
    public function getNormalFirstCategory()
    {
        $data = [
            'status'    =>1,
            'parent_id' =>0,
        ];
        $order = [
            // 'listorder' => 'desc',
            'id' => 'desc',
        ];
        $res = $this->where($data)
                    ->order($order)
                    ->select();
        return $res;
    }

    // 获取子栏目的顶级栏目
    public function getFirstCategory($parentId)
    {
        $data = [
            'parent_id' => $parentId,
            'status' => ['gt',-1],
        ];
        $order = [
            'listorder' => 'desc',
            // 'id' => 'desc',
        ];
        $res = $this->where($data)
                    ->order($order)
                    // ->fetchSql(true) // 生成sql语句
                    ->paginate();
        // echo $this->getLastSql();exit;// 返回生成执行的sql语句
        return $res;
    }

    // 获取父栏目
    public function getCategorysToParentId($parentId=0)
    {
        $data  = [
            'parent_id' => $parentId,
            'status' => 1,
        ];
        $order = [
            'id' => 'desc',
        ];
        // 只选取要使用到的字段
        $field = [
            'id','name','parent_id'
        ];
        $res = $this->where($data)
                    ->field($field)
                    ->order($order)
                    ->select();
        // dump($res);exit();
        return $res;
    }

    public function getNormalRecommendCategoryByParentId($pid=0, $limit=5)
    {
        $data = [
            'parent_id' => $pid,
            'status' => 1,
        ];

        $order = [
            'listorder' => 'desc',
            'id' => 'desc',
        ];

        $res = $this->where($data)->order($order);
        if ($limit) {
            $res = $res->limit($limit);
        }

        return $res->select();
    }

    public function getNormalCategoryIdParentId($ids) {
        $data = [
            'parent_id' => ['in', implode(',', $ids)],
            'status' => 1,
        ];

        $order = [
            'listorder' => 'desc',
            'id' => 'desc',
        ];

        $result = $this->where($data)
            ->order($order)
            ->select();

        return $result;
    }
}
